from django.shortcuts import render
from django_redis import get_redis_connection
from django.http import JsonResponse
from django.views.generic import View
from goods.models import GoodsSKU
from utils.mixin import LoginRequiredMixin
# Create your views here.

class CartAddView(View):
    '''加购物车'''
    def post(self, request):
        sku_id = request.POST.get("sku_id")
        count = request.POST.get("count")

        user = request.user
        if not user.is_authenticated:
            return JsonResponse({"res": 0, "errmsg": '请去登录'})

        if not all([sku_id, count]):
            return JsonResponse({"res": -1, "errmsg": '数据不完整'})

        try:
            count = int(count)
        except Exception:
            return JsonResponse({"res": -1, "errmsg": '输入商品数量异常'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id, is_delete=False)
        except GoodsSKU.DoesNotExist as e:
            return JsonResponse({"res": -1, "errmsg": '该商品可能已下架'})
        print(sku.id)
        conn = get_redis_connection("default")
        cart_key = "cart_%d" % user.id
        cart_nums = conn.hget(cart_key, sku_id)
        print(cart_nums)
        if cart_nums:
            count += int(cart_nums)

        # 校验商品的库存
        if count > sku.stock:
            return JsonResponse({'res': -1, 'errmsg': '商品库存不足'})
        print(count)
        conn.hset(cart_key, sku_id, count)
        cart_count = conn.hlen(cart_key)
        print(cart_count)
        return JsonResponse({"res": 1, "msg": '添加成功', 'cart_count': cart_count})

class CartInfoView(LoginRequiredMixin, View):
    '''购物车视图类'''
    def get(self, request):
        user = request.user
        conn = get_redis_connection('default')
        cart_key = 'cart_%d' % user.id
        cart_dict = conn.hgetall(cart_key)
        skus = []
        total_count = 0
        total_price = 0
        for sku_id, count in cart_dict.items():
            sku = GoodsSKU.objects.get(id=sku_id, is_delete=False)
            sku.count = int(count)
            amount = sku.price*int(count)
            sku.amount = amount
            skus.append(sku)
            total_count += int(count)
            total_price += amount

        context = {
            "skus": skus,
            "total_count": total_count,
            "total_price": total_price
        }

        return render(request, 'cart.html', context)

class CartUpdateView(View):
    '''更新购物车'''
    def post(self, request):
        sku_id = request.POST.get("sku_id")
        count = request.POST.get("count")
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({"res": 0, "errmsg": '请去登录'})

        if not all([sku_id, count]):
            return JsonResponse({"res": -1, "errmsg": '数据不完整'})

        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({"res": -1, "errmsg": '商品数量错误'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except GoodsSKU.DoesNotExist:
            return JsonResponse({"res": -1, "errmsg": '商品不存在'})

        if count > sku.stock:
            return JsonResponse({"res": -1, "errmsg": '商品库存不足'})

        conn = get_redis_connection('default')
        cart_key = 'cart_%d' % user.id

        conn.hset(cart_key, sku_id, count)
        return JsonResponse({"res": 1, "msg": '购物车更新成功'})


class CartDeleteView(View):
    '''删除购物车'''
    def post(self, request):
        sku_id = request.POST.get("sku_id")
        user = request.user

        if not user.is_authenticated:
            return JsonResponse({"res": 0, "errmsg": '请去登录'})

        if not all([sku_id]):
            return JsonResponse({"res": -1, "errmsg": '数据不完整'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except GoodsSKU.DoesNotExist:
            return JsonResponse({"res": -1, "errmsg": '商品不存在'})

        conn = get_redis_connection('default')
        cart_key = 'cart_%d' % user.id
        conn.hdel(cart_key, sku_id)
        return JsonResponse({"res": 1, "msg": '购物车删除成功'})